<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElCard, ElCol, ElRow, ElIcon } from 'element-plus'
import { User, Goods, ShoppingCart, Document } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getStatistics } from '@/api/dashboard/analysis'
import { StatisticsData } from '@/api/dashboard/analysis/types'
import { ContentWrap } from '@/components/ContentWrap'

const loading = ref(false)
const statistics = ref<StatisticsData>({
  productCount: 0,
  orderCount: 0,
  userCount: 0,
  cartCount: 0,
  weeklySales: [],
  monthlySales: []
})

const weeklyChartRef = ref<HTMLDivElement>()
const monthlyChartRef = ref<HTMLDivElement>()
let weeklyChart: echarts.ECharts | null = null
let monthlyChart: echarts.ECharts | null = null

const statisticCards = computed(() => [
  {
    key: 'userCount',
    title: '用户数量',
    value: statistics.value.userCount,
    icon: User,
    color: '#409EFF'
  },
  {
    key: 'productCount',
    title: '商品数量',
    value: statistics.value.productCount,
    icon: Goods,
    color: '#67C23A'
  },
  {
    key: 'orderCount',
    title: '订单数量',
    value: statistics.value.orderCount,
    icon: Document,
    color: '#E6A23C'
  },
  {
    key: 'cartCount',
    title: '购物车商品数量',
    value: statistics.value.cartCount,
    icon: ShoppingCart,
    color: '#909399'
  }
])

const formatNumber = (num: number): string => num.toLocaleString('zh-CN')

// 初始化周内销售额图表（周一到周日，换行显示）
const initWeeklyChart = () => {
  if (!weeklyChartRef.value) return
  weeklyChart = echarts.init(weeklyChartRef.value)

  const weeklyData = statistics.value.weeklySales.map((item) => ({
    name: `周\n${['一', '二', '三', '四', '五', '六', '日'][item.week - 1]}`,
    value: item.salesAmount
  }))

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any) => {
        const day = params[0].name.replace('\n', '')
        return `${day}: ¥${params[0].value}`
      }
    },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      data: weeklyData.map((item) => item.name),
      axisLabel: {
        interval: 0,
        lineHeight: 20
      },
      axisTick: { alignWithLabel: true }
    },
    yAxis: {
      type: 'value',
      axisLabel: { formatter: '¥{value}' }
    },
    series: [
      {
        name: '销售额',
        type: 'bar',
        barWidth: '60%',
        data: weeklyData.map((item) => item.value),
        itemStyle: {
          color: '#409EFF',
          borderRadius: [4, 4, 0, 0]
        }
      }
    ]
  }

  weeklyChart.setOption(option)
}

// 初始化每月销售额图表（一月到十二月，换行显示）
const initMonthlyChart = () => {
  if (!monthlyChartRef.value) return
  monthlyChart = echarts.init(monthlyChartRef.value)

  const monthlyData = statistics.value.monthlySales.map((item) => ({
    name: `${item.month}\n月`,
    value: item.salesAmount
  }))

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const month = params[0].name.replace('\n', '')
        return `${month}: ¥${params[0].value}`
      }
    },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: monthlyData.map((item) => item.name),
      axisLabel: {
        interval: 0,
        lineHeight: 20
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: { formatter: '¥{value}' }
    },
    series: [
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
          ])
        },
        data: monthlyData.map((item) => item.value),
        itemStyle: { color: '#409EFF' }
      }
    ]
  }

  monthlyChart.setOption(option)
}

const fetchStatistics = async () => {
  loading.value = true
  try {
    const res = await getStatistics()
    if (res.code === 200) {
      statistics.value = res.data
      initWeeklyChart()
      initMonthlyChart()
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

const handleResize = () => {
  weeklyChart?.resize()
  monthlyChart?.resize()
}

onMounted(() => {
  fetchStatistics()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  weeklyChart?.dispose()
  monthlyChart?.dispose()
})
</script>
<template>
  <ContentWrap>
    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :xs="24" :sm="12" :md="6" v-for="item in statisticCards" :key="item.key">
        <el-card class="statistic-card" shadow="hover">
          <div class="flex justify-between items-center">
            <div>
              <p class="text-gray-500 text-sm">{{ item.title }}</p>
              <p class="text-2xl font-bold mt-2">{{ formatNumber(item.value) }}</p>
            </div>
            <el-icon :size="40" :color="item.color">
              <component :is="item.icon" />
            </el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 - 上下排列 -->
    <el-row :gutter="16">
      <!-- 周内销售额柱状图（占满一行） -->
      <el-col :xs="24">
        <el-card class="chart-card" v-loading="loading">
          <template #header>
            <span class="font-medium">周内销售额</span>
          </template>
          <div ref="weeklyChartRef" class="h-80"></div>
        </el-card>
      </el-col>

      <!-- 每月销售额面积图（占满一行） -->
      <el-col :xs="24">
        <el-card class="chart-card" v-loading="loading">
          <template #header>
            <span class="font-medium">每月销售额</span>
          </template>
          <div ref="monthlyChartRef" class="h-80"></div>
        </el-card>
      </el-col>
    </el-row>
  </ContentWrap>
</template>

<style scoped lang="scss">
.statistic-card {
  margin-bottom: 16px;
  &:hover {
    transform: translateY(-2px);
    transition: transform 0.3s;
  }
}

.chart-card {
  margin-bottom: 16px;
  :deep(.el-card__header) {
    padding: 12px 20px;
    border-bottom: 1px solid var(--el-border-color-light);
  }
}

.h-80 {
  height: 320px;
}
</style>
